package simtools.xml;

import java.util.HashMap;
import java.util.Iterator;

import org.jdom.Document;
import org.jdom.Element;

import p2pcdnsim.network.Node;
import p2pcdnsim.network.RouterNode;

public class ClientPlacement {
	
	private Document requests;
	private Document clientPlacement;
	private HashMap<String, String> links;
	private HashMap<String,RouterNode> nodeMap;
	private HashMap<RouterNode,Integer> routersRequests;
	
	
	
	public ClientPlacement(Document requests,Document clientPlacement, Node[] nodes){
		this.requests = requests;
		this.clientPlacement = clientPlacement;
		
		this.routersRequests = new HashMap<RouterNode, Integer>();
		this.nodeMap = new HashMap<String,RouterNode>();
		this.links = new HashMap<String, String>();
		
		for (int i = 0; i < nodes.length; i++) {
			
			this.routersRequests.put((RouterNode) nodes[i], 0);
			this.nodeMap.put(((RouterNode)nodes[i]).getName(), (RouterNode) nodes[i]);
			
		}
		
		getClientPlacements();
		countRequests();
	
		
	}
	
	public void getClientPlacements(){
		
		Iterator<?> clientPlacementIt = this.clientPlacement.getRootElement().getChildren("Placement").iterator();
		while(clientPlacementIt.hasNext()) {
			Element root  	   = (Element) clientPlacementIt.next();
			String client   = root.getChild("Client").getText();
			String router = root.getChild("Router").getText();
			
			//Mudar isso aqui
			this.links.put(client, "RouterNode"+router);
		}
		
	}
	
	public void countRequests(){
		
		Iterator<?> requestsIt = this.requests.getRootElement().getChildren("Request").iterator();
		while(requestsIt.hasNext()) {
			Element root  	   = (Element) requestsIt.next();
			String client   = root.getChild("Client").getText();
			
			int temp;
			temp = this.routersRequests.get(this.nodeMap.get(this.links.get(client))) + 1;
			//RouterNode routerTemp = this.nodeMap.get(this.links.get(client));
			this.routersRequests.remove(this.nodeMap.get(this.links.get(client)));
			this.routersRequests.put(this.nodeMap.get(this.links.get(client)), temp);
			
		}
		
	}

	public HashMap<RouterNode, Integer> getRoutersRequests() {
		return routersRequests;
	}
}
